package fitness

import (
	"fitness/internal/entity/fitness"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type DetailDao struct {
	DB  *gorm.DB
	Log *zap.Logger
}

func NewDetailDao(db *gorm.DB, logger *zap.Logger) *DetailDao {
	return &DetailDao{
		DB:  db,
		Log: logger,
	}
}

// QueryDetailList 查询列表
func (d *DetailDao) QueryDetailList(fitnessDate *uint64, isDeleted *uint8) ([]fitness.Detail, error) {
	var list []fitness.Detail
	tx := d.DB.Model(&fitness.Detail{}).Where("fitness_date = ?", *fitnessDate)
	if isDeleted != nil {
		tx.Where("is_deleted = ?", *isDeleted)
	}
	err := tx.Find(&list).Error
	return list, err
}

func (d *DetailDao) Insert(query fitness.Detail) (fitness.Detail, error) {
	if query.IsDeleted == nil {
		var deleted = uint8(0)
		query.IsDeleted = &deleted
	}
	err := d.DB.Create(&query).Error
	return query, err
}

func (d *DetailDao) Update(query fitness.Detail) (fitness.Detail, error) {
	if query.IsDeleted == nil {
		var deleted = uint8(0)
		query.IsDeleted = &deleted
	}
	err := d.DB.Updates(&query).Error
	return query, err
}

func (d *DetailDao) DeleteById(id uint64) error {
	err := d.DB.Model(&fitness.Detail{}).
		Where("id = ?", id).
		Update("is_deleted", 1).Error
	return err
}

type CourseStats struct {
	Date  int `gorm:"column:date"`  // 对应查询的date字段
	Count int `gorm:"column:count"` // 对应查询的count字段
}

func (d *DetailDao) Courses(startDate int, endDate int) ([]CourseStats, error) {
	querySQL := `
      SELECT 
        fitness_date as date,
        COUNT(*) as count 
      FROM 
        fitness_detail 
      WHERE 
        fitness_date BETWEEN ? AND ? 
      GROUP BY 
        fitness_date
    `
	var statsList []CourseStats
	err := d.DB.Raw(querySQL, startDate, endDate).Scan(&statsList).Error

	return statsList, err
}
